package org.dtrd.modules.system.util.qywx.externalcontact;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jeecg.qywx.api.base.JwAccessTokenAPI;
import com.jeecg.qywx.api.core.common.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.dtrd.modules.system.entity.bean.qiyeweixin.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 企业微信外部联系人相关API
 *
 * @author 萧
 * @date:2021-11-08 3:03 下午
 **/
@Slf4j
public class JwExternalContactAPI {

    /**
     * 外部联系人Secret
     */
    private static final String EXTERNALCONTACTSECRET = "-jI0vMFkzAgJTkiNctDOh5xrzxHRQIpdTQsWVTqV-xQ";

    /**
     * 获取配置了客户联系功能的成员列表
     * https://open.work.weixin.qq.com/api/doc/90000/90135/92571
     */
    private static final String GET_FOLLOW_USER_LIST = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_follow_user_list?access_token=ACCESS_TOKEN";

    /**
     * 获取客户列表
     * https://open.work.weixin.qq.com/api/doc/90000/90135/92113
     */
    private static final String CLIENT_LIST = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=ACCESS_TOKEN&userid=USERID";

    /**
     * 获取客户详情
     * https://open.work.weixin.qq.com/api/doc/90000/90135/92114
     */
    private static final String GET_CLIENT_BY_USER = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=ACCESS_TOKEN&external_userid=EXTERNAL_USERID";

    /**
     * 批量获取客户详情
     * https://open.work.weixin.qq.com/api/doc/90000/90135/92994
     */
    private static final String BATCH_GET_CLIENT_BY_USER = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user?access_token=ACCESS_TOKEN";

    /**
     * 获取群详情
     */
    private static final String GROUPCHAT = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get?access_token=ACCESS_TOKEN";

    public static String getAccessToken(String clientId, String secret) {
        AccessToken accessToken = JwAccessTokenAPI.getAccessToken(clientId, secret);
        return Optional.ofNullable(accessToken).map(AccessToken::getAccesstoken).orElse(null);
    }

    /**
     * 获取配置了客户联系功能的成员列表
     *
     * @param accessToken
     * @return
     */
    public static List<String> getFollowUserList(String accessToken) {
        String requestUrl = GET_FOLLOW_USER_LIST.replace("ACCESS_TOKEN", accessToken);
        String responseStr = HttpUtil.get(requestUrl);
        if (isResponseSuccess(responseStr)) {
            QwFollowUserList qwFollowUserList = JSONObject.parseObject(responseStr, QwFollowUserList.class);
            return Optional.ofNullable(qwFollowUserList).map(QwFollowUserList::getFollow_user).orElse(null);
//            JSONObject jsonObject = JSONObject.parseObject(responseStr);
//            if (jsonObject.containsKey(FOLLOW_USER)) {
//                JSONArray followUserArray = jsonObject.getJSONArray(FOLLOW_USER);
//                if (followUserArray != null) {
//                    List<String> list = new ArrayList<>(followUserArray.size());
//                    followUserArray.stream().map(String::valueOf).forEach(list::add);
//                    return list;
//                }
//            }
        } else {
            log.info("JwExternalContactAPI.getFollowUserList.[accessToken] 请求失败  response= " + responseStr);
        }
        return null;
    }

    /**
     * 获取客户列表
     *
     * @param accessToken
     * @param userId
     * @return
     */
    public static List<String> getClientList(String accessToken, String userId) {
        String requestUrl = CLIENT_LIST.replace("ACCESS_TOKEN", accessToken).replace("USERID", userId);
        String responseStr = HttpUtil.get(requestUrl);
//        log.info("JwExternalContactAPI.getClientList.[accessToken, userId] " + requestUrl + " ;\n responseStr=" + responseStr);
        if (isResponseSuccess(responseStr)) {
            QwClientList qwClientList = JSONObject.parseObject(responseStr, QwClientList.class);
            return Optional.ofNullable(qwClientList).map(QwClientList::getExternal_userid).orElse(null);
        } else {
            log.info("JwExternalContactAPI.getClientList.[accessToken, userId] 请求失败  response= " + responseStr);
        }
        return null;
    }

    private static boolean isResponseSuccess(String responseStr) {
        return Optional.of(responseStr).map(str -> JSONObject.parseObject(responseStr, QwResponse.class)).map(QwResponse::isResponseSuccess).orElse(false);
    }

    /**
     * 客户详情
     *
     * @param accessToken
     * @param clientId
     * @return
     */
    public static QwClientInfoResponse getClientDetail(String accessToken, String clientId) {
        String requestUrl = GET_CLIENT_BY_USER.replace("ACCESS_TOKEN", accessToken).replace("EXTERNAL_USERID", clientId);
        String responseStr = HttpUtil.get(requestUrl);
        if (isResponseSuccess(responseStr)) {
            QwClientInfoResponse infoResponse = JSONObject.parseObject(responseStr, QwClientInfoResponse.class);
            return infoResponse;
        } else {
            log.info("JwExternalContactAPI.getClientDetail.[accessToken, clientId] 请求失败  response= " + responseStr);
        }
        return null;
    }

    public static QwClientInfoListResponse batchGetClientDetail(String accessToken, List<String> clientIdList, String cursor) {
        QwClientListRequest request = new QwClientListRequest();
        request.setCursor(cursor);
        request.setUserid_list(clientIdList);
        String requestUrl = BATCH_GET_CLIENT_BY_USER.replace("ACCESS_TOKEN", accessToken);
        String responseStr = HttpUtil.post(requestUrl, JSON.toJSONString(request));
        if (isResponseSuccess(responseStr)) {
            QwClientInfoListResponse infoResponse = JSONObject.parseObject(responseStr, QwClientInfoListResponse.class);
            return infoResponse;
        } else {
            log.info("JwExternalContactAPI.batchGetClientDetail.[accessToken, clientIdList, cursor] 请求失败  response= " + responseStr);
        }
        return null;
    }

    /**
     * 获取客户群详情
     *
     * @param accessToken
     * @param request
     * @return
     */
    public static QwGroupInfoResponse getGroupInfo(String accessToken, QwGroupInfoRequest request) {
        String requestUrl = GROUPCHAT.replace("ACCESS_TOKEN", accessToken);
        String responseStr = HttpUtil.post(requestUrl, JSON.toJSONString(request));
        if (isResponseSuccess(responseStr)) {
            QwGroupInfoResponse infoResponse = JSONObject.parseObject(responseStr, QwGroupInfoResponse.class);
            return infoResponse;
        } else {
            log.info("JwExternalContactAPI.getGroupInfo.[accessToken, request] 请求失败  response= " + responseStr);
        }
        return null;
    }
}
